﻿#region Imports
using System.Timers;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Markup;
using BookManager.ViewModels;
#endregion Imports

namespace BookManager
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        //Timer tmr = new Timer { Interval = 200 };
        //int splashDuration = 1500;
        MainViewModel mainViewModel = new MainViewModel();

        #region Constructors
        public MainWindow()
        {
            InitializeComponent();
            itmctrlBookList.Items.Clear();
            itmctrlBookShelf.Items.Clear();

            this.DataContext = mainViewModel;

            //tmr.Elapsed += new ElapsedEventHandler(tmr_Elapsed);
            //tmr.Start();
        }
        #endregion Constructors

        //public void tmr_Elapsed(object sender, ElapsedEventArgs e)
        //{
        //    imgLogo.Height = imgLogo.Width = imgLogo.Height *= 0.9;
        //
        //    if (splashDuration <= 0)
        //    {
        //        tmr.Stop();
        //        this.DataContext = new MainViewModel();
        //    }
        //
        //    tmr.Stop();
        //    tmr.Start();
        //    splashDuration -= 20;
        //}

        private void scrlBookShelf_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            // var itemWidth = mainViewModel.MySettings.BookShelfItemWidth; // Convert.ToDouble(this.TryFindResource("BookShelfItemWidth"));
            var width = scrlBookShelf.ActualWidth - 18; // Math.Floor((scrlBookShelf.ActualWidth - 18) / itemWidth) * itemWidth + 18; // Math.Floor(scrlBookShelf.ActualWidth / itemWidth) * itemWidth;

            string xaml = @"<ItemsPanelTemplate xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'> <WrapPanel Width=""" + width + " \" /> </ItemsPanelTemplate>";
            itmctrlBookShelf.ItemsPanel = XamlReader.Parse(xaml) as ItemsPanelTemplate;
        }

        private void txtSearchBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter) mainViewModel.SearchBookCommand.Execute(mainViewModel.SearchText);
            else if (e.Key == Key.Escape) mainViewModel.ClearSearchTextCommand.Execute(null);
        }

        //when opened, set focus on control. this will allow closing with ESC.
    }
}
